package bist.believeinstep.impl;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import bist.believeinstep.dao.CompanyDAO;
import bist.believeinstep.dao.ConnectionDAO;
import bist.believeinstep.domain.Company;
import bist.believeinstep.mapper.CompanyMapper;

public class CompanyTemplate implements ConnectionDAO, CompanyDAO {

	private JdbcTemplate jdbcTemplate;
	
	@Override
	public void setDataSource(DataSource dataSource) {
		jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	@Override
	public boolean create(Company company) {
		String query = "INSERT INTO bist_companies(name, dob, tax_code, website, address, email, hotline, phone, cellphone, created_date, modified_date, created_by, modified_by)" +
				" VALUE(?,?,?,?,?,?,?,?,?,?,?,?,?)";
		try {
			jdbcTemplate.update(query, new Object[]{
					company.getName(),
					company.getDob(),
					company.getTaxCode(),
					company.getWebsite(),
					company.getAddress(),
					company.getEmail(),
					company.getHotline(),
					company.getPhone(),
					company.getCellphone(),
					company.getCreated(),
					company.getModified(),
					company.getCreatedBy(),
					company.getModifiedBy()
			});
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean update(Company company) {
		String query  = "UPDATE bist_companies" +
				" SET name = ?" +
				" dob = ?" +
				" tax_code = ?" +
				" website = ?" +
				" address = ?" +
				" email = ?" +
				" hotline = ?" +
				" phone = ?" +
				" cellphone = ?" +
				" modified_date = ?" +
				" modified_by = ?" +
				" WHERE id = ?";
		try {
			jdbcTemplate.update(query, new Object[]{
					company.getName(),
					company.getDob(),
					company.getTaxCode(),
					company.getWebsite(),
					company.getAddress(),
					company.getEmail(),
					company.getHotline(),
					company.getPhone(),
					company.getCellphone(),
					company.getModified(),
					company.getModifiedBy(),
					company.getId()
			});
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean delete(int id) {
		String query = "DELETE bist_companies WHERE id = ?";
		try {
			jdbcTemplate.update(query, new Object[]{id});
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public Company find(int id) {
		String query = "SELECT * FROM bist_companies WHERE id = ?";
		try {
			Company company = jdbcTemplate.queryForObject(query, new Object[]{id}, new CompanyMapper());
			return company;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
